package com.example.rwq_test.leetcode;

/**
 * 两链表数相加
 *
 * @author renweiqiang
 * @version 1.0.0
 * @createTime 2023/9/4
 */
public class TwoListAdd {
    static class ListNode {
        int value;
        ListNode next;

        ListNode(int value) {
            this.value = value;
        }
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(2);
        ListNode l11 = l1;
        l11.next = new ListNode(4);
        l11 = l11.next;
        l11.next = new ListNode(3);
        ListNode l2 = new ListNode(5);
        ListNode l22 = l2;
        l22.next = new ListNode(6);
        l22 = l22.next;
        l22.next = new ListNode(4);
        ListNode result = addTwoNumbers(l1, l2);
        while (result != null) {
            System.out.print(result.value + " ");
            result = result.next;
        }
    }

    private static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode pre = new ListNode(0);
        ListNode cur = pre;
        int carry = 0;
        while (l1 != null || l2 != null) {
            int x = l1 == null ? 0 : l1.value;
            int y = l2 == null ? 0 : l2.value;
            int sum = x + y + carry;

            carry = sum / 10;
            sum = sum % 10;
            cur.next = new ListNode(sum);

            cur = cur.next;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }

        if (carry == 1) {
            cur.next = new ListNode(carry);
        }
        return pre.next;
    }
}
